<template>
  <el-card class="box-card">
    <el-button type="primary" size="default" style="margin-bottom: 20px;" icon="Plus"
      @click="handleAddClick">添加品牌</el-button>


    <el-table :data="tableData" border size="large" class="table-container">
      <el-table-column type="index" label="序号" width="180" align="center" />
      <el-table-column prop="name" label="品牌名" align="center" />
      <el-table-column prop="logoUrl" label="logo" align="center">
        <template #="{ row, $index }">
          <img :src="row.logoUrl" alt="" style="width: 50px; height: 50px; object-fit: cover; border-radius: 5px;" />
        </template>

      </el-table-column>
      <el-table-column label="操作" width="180" align="center">
        <template #="{ row, $index }">
          <el-button type="primary" @click="handleEditClick(row.id)">
            编辑
          </el-button>
          <el-popconfirm confirm-button-text="是" cancel-button-text="否" :hide-icon="true" title="确认删除吗?"
            @confirm="handleDeleteClick(row.id)">
            <template #reference>
              <el-button type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>

    </el-table>

    <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[3, 5, 7, 9]" :size="size"
      :background="background" layout="prev, pager, next, jumper, ->, total, sizes," :total="total"
      @size-change="handleSizeChange" @current-change="handleCurrentChange" style="margin: 20px 0;" />


    <el-dialog v-model="dialogVisible" :modal="true">
      <template #header="{ titleId, titleClass }">
        <div class="my-header">
          <h4 :id="titleId" :class="titleClass">{{ formTitle }}</h4>
        </div>
      </template>

      <el-form ref="productFormRef" :rules="productFormRules" :model="productForm" label-width="auto"
        style="max-width: 600px">
        <el-form-item label="品牌名" v-show="false" prop="id">
          <el-input v-model="productForm.id" />
        </el-form-item>
        <el-form-item label="品牌名" prop="name">
          <el-input v-model="productForm.name" />
        </el-form-item>
        <el-form-item label="品牌logo" prop="logoUrl">
          <el-upload class="avatar-uploader" name="file" action="/api/oss/upload" :data="{ path: 'product' }" :headers="uploadHeaders"
           :with-credentials="true" :show-file-list="true" :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="productForm.logoUrl" :src="productForm.logoUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">Cancel</el-button>
          <el-button type="primary" @click="dialogConfirm">
            Confirm
          </el-button>
        </div>
      </template>
    </el-dialog>

  </el-card>
</template>

<script setup lang='ts'>
import { onMounted, ref, reactive, computed, nextTick } from 'vue';
import { pageQueryApi, productDetailApi, productSaveApi, productDeleteApi } from '@/api/product';
import type { UploadProps } from 'element-plus'
import { ElMessage } from 'element-plus'
import type { ProductFormInterface } from './types';
import useUserStore from '@/store/modules/user';


let pageNum = ref(1);
let size = ref('large');
let background = ref(true);
let pageSize = ref(3);
let total = ref(20);
const tableData = ref([]);
const dialogVisible = ref(false)
const useStore = useUserStore();

const uploadHeaders = computed(() => ({
  // Authorization: `Bearer ${useStore.token}`,
  TOKEN: useStore.token,
  // 注意：这里不需要设置 Content-Type，el-upload 会自动设置 multipart/form-data
}));

// 定义表单的引用
let productFormRef = ref();
// 定义表单数据
let productForm = reactive<ProductFormInterface>({
  id: '',
  name: '',
  logoUrl: ''
});
const formTitle = computed(() => {
  return productForm.id ? '编辑品牌' : '添加品牌';
});

const productFormRules = {
  name: [
    { required: true, message: '请输入品牌名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符之间', trigger: 'blur' }
  ],
  logoUrl: [
    { required: true, message: '请上传品牌logo', trigger: 'change' }
  ]
};


const refreshTableData = async (page = 1) => {
  // 初始化表格数据
  tableData.value = [];
  pageNum.value = page;
  // 页面加载时可以调用接口获取数据
  let result = await pageQueryApi(pageNum.value, pageSize.value);
  total.value = result.total;
  tableData.value = result.recordList;
};

onMounted(() => {
  refreshTableData()

});

function handleAddClick() {
  // 添加操作
  dialogVisible.value = true;
  nextTick(() => {
    // 确保表单重置在对话框显示后执行
    productFormRef.value.resetFields(); // 重置表单
    console.log('productForm', productForm);
    console.log('productFormRef', productFormRef.value);

  });

}

// 页码发生变化
function handleCurrentChange() {

  refreshTableData(pageNum.value);
}
// 每页展示条数 发生变化
function handleSizeChange() {
  refreshTableData();
}

function handleEditClick(id: number) {
  // 编辑操作
  dialogVisible.value = true
  console.log('编辑操作 id', id);
  productDetailApi(id).then((res: any) => {
    productForm.id = res.id;
    productForm.name = res.name;
    productForm.logoUrl = res.logoUrl;
  });
}

// 模态框确认
async function dialogConfirm() {

  // 校验表单
  await productFormRef.value.validate((valid: any) => {
    if (!valid) {
      throw new Error('表单验证失败，请检查输入');
    }
  })

  dialogVisible.value = false;
  // 提交表单
  productSaveApi(productForm).then(() => {
    ElMessage.success('编辑成功');
    refreshTableData(pageNum.value);
  });
}

function handleDeleteClick(id: number) {
  // 删除操作
  productDeleteApi(id).then(() => {
    ElMessage.success('删除成功');
    refreshTableData(pageNum.value);
  }).catch((error: any) => {
    ElMessage.error(error.message || '删除失败');
  });
}

const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  // form.imageUrl = URL.createObjectURL(uploadFile.raw!)
  // 这里没走 axios 的拦截器，所以需要手动判断code
  if (response.code === 200) {
    productForm.logoUrl = response.data;
  } else {
    ElMessage.error(response.message || '上传失败');
    return;
  }

}

// 上传文件前 校验
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  // if (rawFile.type !== 'image/jpeg') {
  //   ElMessage.error('Avatar picture must be JPG format!')
  //   return false
  // } else if (rawFile.size / 1024 / 1024 > 2) {
  //   ElMessage.error('Avatar picture size can not exceed 2MB!')
  //   return false
  // }
  return true
}


</script>
<style scoped>
.box-card {
  width: 100%;
  height: 100%;
}

.table-container {
  height: 500px;
  overflow: auto;
}

el-button {
  cursor: pointer;
}

.my-header {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  gap: 16px;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>